<template>
  <div 
    class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4"
    v-if="visible"
    @click="handleOverlayClick"
  >
    <!-- 模态框容器 -->
    <div 
      class="bg-white rounded-lg shadow-xl w-full max-w-4xl mx-auto max-h-[90vh] flex flex-col transform transition-all duration-300 scale-100"
      @click.stop
    >
      <!-- 模态框头部 -->
      <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
        <h3 class="text-lg font-medium text-gray-900">
          角色权限 - {{ role.name }}
        </h3>
        <div class="flex items-center gap-3">
          <button
            type="button"
            class="text-sm text-purple-600 hover:text-purple-800 focus:outline-none"
            @click="selectAllPermissions"
          >
            <i class="fa fa-check-square mr-1"></i>全选
          </button>
          <button
            type="button"
            class="text-sm text-gray-600 hover:text-gray-800 focus:outline-none"
            @click="deselectAllPermissions"
          >
            <i class="fa fa-square mr-1"></i>清空
          </button>
          <button 
            class="text-gray-400 hover:text-gray-500 focus:outline-none"
            @click="handleClose"
            aria-label="关闭"
          >
            <i class="fa fa-times"></i>
          </button>
        </div>
      </div>
      
      <!-- 模态框内容 -->
      <div class="px-6 py-5 flex-1 overflow-y-auto">
        <!-- 权限过滤 -->
        <div class="mb-4 relative">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索权限..."
            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition-colors"
          >
          <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
          <button
            v-if="searchQuery"
            class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
            @click="searchQuery = ''"
          >
            <i class="fa fa-times-circle"></i>
          </button>
        </div>
        
        <!-- 继承权限提示 -->
        <div v-if="role.inheritedPermissions && role.inheritedPermissions.length > 0" class="mb-4 bg-blue-50 border-l-4 border-blue-400 p-3 rounded">
          <div class="flex">
            <div class="flex-shrink-0">
              <i class="fa fa-info-circle text-blue-500"></i>
            </div>
            <div class="ml-3">
              <p class="text-sm text-blue-700">
                该角色从其他角色继承了 <span class="font-medium">{{ role.inheritedPermissions.length }}</span> 项权限，这些权限未在下方显示但角色实际拥有。
              </p>
            </div>
          </div>
        </div>
        
        <!-- 权限树 -->
        <div class="space-y-3">
          <template v-if="filteredPermissionGroups.length === 0 && !loading">
            <div class="text-center py-10 text-gray-500">
              <i class="fa fa-key text-3xl mb-2"></i>
              <p>没有找到匹配的权限</p>
              <button
                class="mt-2 text-purple-600 hover:text-purple-800 text-sm"
                @click="searchQuery = ''"
                v-if="searchQuery"
              >
                清除搜索条件
              </button>
            </div>
          </template>
          
          <template v-if="loading">
            <div v-for="i in 3" :key="i" class="animate-pulse">
              <div class="h-6 bg-gray-200 rounded w-40 mb-2"></div>
              <div class="pl-6 space-y-2">
                <div v-for="j in 2" :key="j" class="h-5 bg-gray-200 rounded w-60"></div>
              </div>
            </div>
          </template>
          
          <template v-else>
            <div v-for="group in filteredPermissionGroups" :key="group.id" class="permission-group">
              <!-- 权限组 -->
              <div class="flex items-center py-2">
                <label class="inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    class="form-checkbox h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded transition-colors"
                    :checked="isGroupFullySelected(group)"
                    :indeterminate="isGroupPartiallySelected(group)"
                    @change="handleGroupChange(group, $event.target.checked)"
                    :disabled="isSystemRole"
                  >
                  <span class="ml-2 font-medium text-gray-800">{{ group.name }}</span>
                  <span class="ml-2 text-xs text-gray-500">({{ getGroupSelectedCount(group) }}/{{ group.permissions.length }})</span>
                </label>
                <button
                  class="ml-2 text-gray-400 hover:text-gray-600 text-xs"
                  @click="toggleGroup(group.id)"
                >
                  <i :class="isGroupExpanded(group.id) ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i>
                </button>
              </div>
              
              <!-- 权限项 -->
              <div v-if="isGroupExpanded(group.id)" class="pl-6 mt-1 border-l-2 border-gray-100 space-y-2 pb-2">
                <div v-for="permission in group.permissions" :key="permission.id" class="permission-item">
                  <label class="inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      class="form-checkbox h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded transition-colors"
                      :checked="isPermissionSelected(permission.id)"
                      :disabled="isSystemRole || (permission.isSystemPermission && !isPermissionSelected(permission.id))"
                      @change="handlePermissionChange(permission.id, $event.target.checked)"
                    >
                    <span class="ml-2 text-sm text-gray-700">{{ permission.name }}</span>
                    <span class="ml-2 text-xs font-mono text-gray-500">{{ permission.code }}</span>
                    <span v-if="permission.isSystemPermission" class="ml-2 text-xs px-1.5 py-0.5 bg-gray-100 text-gray-600 rounded">
                      系统权限
                    </span>
                  </label>
                  <p v-if="permission.description" class="ml-6 mt-1 text-xs text-gray-500">
                    {{ permission.description }}
                  </p>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
      
      <!-- 模态框底部 -->
      <div class="px-6 py-4 bg-gray-50 rounded-b-lg flex justify-end space-x-3">
        <button
          type="button"
          class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 transition-colors"
          @click="handleClose"
          :disabled="loading"
        >
          取消
        </button>
        <button
          type="button"
          class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-purple-600 hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 transition-colors"
          @click="handleSave"
          :disabled="loading || isSystemRole || !hasPermissionChanges"
        >
          <i v-if="loading" class="fa fa-spinner fa-spin mr-1"></i>
          保存权限
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch, computed } from 'vue';

// 将扁平权限列表转换为按组组织的结构
const groupPermissions = (permissions) => {
  const groups = {};
  
  permissions.forEach(permission => {
    const groupId = permission.groupId;
    
    if (!groups[groupId]) {
      groups[groupId] = {
        id: groupId,
        name: permission.groupName || '未分组',
        permissions: []
      };
    }
    
    groups[groupId].permissions.push(permission);
  });
  
  // 转换为数组并按组名称排序
  return Object.values(groups).sort((a, b) => a.name.localeCompare(b.name));
};

export default {
  props: {
    // 控制模态框显示/隐藏
    visible: {
      type: Boolean,
      default: false
    },
    // 角色信息
    role: {
      type: Object,
      required: true,
      default: () => ({ id: null, name: '', isSystemRole: false, inheritedPermissions: [] })
    },
    // 所有权限列表
    permissions: {
      type: Array,
      default: () => []
    },
    // 加载状态
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: ['close', 'save'],
  setup(props, { emit }) {
    // 搜索查询
    const searchQuery = ref('');
    
    // 展开的权限组
    const expandedGroups = ref([]);
    
    // 初始选中的权限ID
    const initialSelectedPermissionIds = ref([]);
    
    // 当前选中的权限ID
    const selectedPermissionIds = ref([]);
    
    // 按组组织的权限
    const permissionGroups = computed(() => {
      return groupPermissions(props.permissions);
    });
    
    // 根据搜索过滤权限组
    const filteredPermissionGroups = computed(() => {
      if (!searchQuery.value) {
        return permissionGroups.value;
      }
      
      const query = searchQuery.value.toLowerCase();
      
      return permissionGroups.value
        .map(group => {
          // 过滤组内权限
          const filteredPermissions = group.permissions.filter(permission => 
            permission.name.toLowerCase().includes(query) ||
            permission.code.toLowerCase().includes(query) ||
            (permission.description && permission.description.toLowerCase().includes(query))
          );
          
          return {
            ...group,
            permissions: filteredPermissions
          };
        })
        // 过滤掉没有权限的组
        .filter(group => group.permissions.length > 0);
    });
    
    // 系统角色判断
    const isSystemRole = computed(() => props.role.isSystemRole);
    
    // 监听角色变化，初始化选中的权限
    watch(() => props.role, (newRole) => {
      if (newRole && newRole.permissions) {
        initialSelectedPermissionIds.value = newRole.permissions.map(p => p.id);
        selectedPermissionIds.value = [...initialSelectedPermissionIds.value];
        
        // 默认展开所有有权限的组
        if (permissionGroups.value.length > 0) {
          const groupsWithPermissions = permissionGroups.value
            .filter(group => group.permissions.some(p => 
              initialSelectedPermissionIds.value.includes(p.id)
            ));
          
          expandedGroups.value = groupsWithPermissions.map(g => g.id);
          
          // 如果没有展开的组，默认展开第一个组
          if (expandedGroups.value.length === 0 && permissionGroups.value.length > 0) {
            expandedGroups.value = [permissionGroups.value[0].id];
          }
        }
      }
    }, { immediate: true, deep: true });
    
    // 监听模态框显示状态
    watch(() => props.visible, (isVisible) => {
      if (!isVisible) {
        searchQuery.value = '';
      }
    });
    
    // 检查权限是否被选中
    const isPermissionSelected = (permissionId) => {
      return selectedPermissionIds.value.includes(permissionId);
    };
    
    // 检查权限组是否完全选中
    const isGroupFullySelected = (group) => {
      return group.permissions.every(permission => 
        isPermissionSelected(permission.id)
      );
    };
    
    // 检查权限组是否部分选中
    const isGroupPartiallySelected = (group) => {
      const selectedCount = group.permissions.filter(permission => 
        isPermissionSelected(permission.id)
      ).length;
      
      return selectedCount > 0 && selectedCount < group.permissions.length;
    };
    
    // 获取组内选中的权限数量
    const getGroupSelectedCount = (group) => {
      return group.permissions.filter(permission => 
        isPermissionSelected(permission.id)
      ).length;
    };
    
    // 检查权限组是否展开
    const isGroupExpanded = (groupId) => {
      return expandedGroups.value.includes(groupId);
    };
    
    // 切换权限组展开状态
    const toggleGroup = (groupId) => {
      const index = expandedGroups.value.indexOf(groupId);
      if (index > -1) {
        expandedGroups.value.splice(index, 1);
      } else {
        expandedGroups.value.push(groupId);
      }
    };
    
    // 处理权限组选择变化
    const handleGroupChange = (group, checked) => {
      if (isSystemRole.value) return;
      
      // 过滤掉系统权限（如果未选中则不能选中）
      const permissionsToUpdate = group.permissions.filter(permission => 
        !permission.isSystemPermission || isPermissionSelected(permission.id)
      );
      
      if (checked) {
        // 选中组内所有权限
        permissionsToUpdate.forEach(permission => {
          if (!isPermissionSelected(permission.id)) {
            selectedPermissionIds.value.push(permission.id);
          }
        });
      } else {
        // 取消选中组内所有权限
        selectedPermissionIds.value = selectedPermissionIds.value.filter(id => 
          !permissionsToUpdate.some(permission => permission.id === id)
        );
      }
    };
    
    // 处理权限项选择变化
    const handlePermissionChange = (permissionId, checked) => {
      if (isSystemRole.value) return;
      
      if (checked && !isPermissionSelected(permissionId)) {
        selectedPermissionIds.value.push(permissionId);
      } else if (!checked && isPermissionSelected(permissionId)) {
        selectedPermissionIds.value = selectedPermissionIds.value.filter(id => id !== permissionId);
      }
    };
    
    // 全选所有权限
    const selectAllPermissions = () => {
      if (isSystemRole.value) return;
      
      const allSelectablePermissions = props.permissions
        .filter(permission => !permission.isSystemPermission || isPermissionSelected(permission.id));
      
      selectedPermissionIds.value = allSelectablePermissions.map(p => p.id);
    };
    
    // 取消所有权限选择
    const deselectAllPermissions = () => {
      if (isSystemRole.value) return;
      
      // 保留系统权限的选中状态
      selectedPermissionIds.value = selectedPermissionIds.value.filter(id => {
        const permission = props.permissions.find(p => p.id === id);
        return permission && permission.isSystemPermission;
      });
    };
    
    // 检查权限是否有变化
    const hasPermissionChanges = computed(() => {
      if (initialSelectedPermissionIds.value.length !== selectedPermissionIds.value.length) {
        return true;
      }
      
      // 检查每个ID是否相同
      return initialSelectedPermissionIds.value.some(id => 
        !selectedPermissionIds.value.includes(id)
      );
    });
    
    // 处理保存
    const handleSave = () => {
      if (!isSystemRole.value) {
        emit('save', props.role.id, selectedPermissionIds.value);
      }
    };
    
    // 处理关闭
    const handleClose = () => {
      emit('close');
    };
    
    // 点击遮罩层关闭
    const handleOverlayClick = () => {
      handleClose();
    };
    
    return {
      searchQuery,
      expandedGroups,
      filteredPermissionGroups,
      loading: props.loading,
      isSystemRole,
      isPermissionSelected,
      isGroupFullySelected,
      isGroupPartiallySelected,
      getGroupSelectedCount,
      isGroupExpanded,
      toggleGroup,
      handleGroupChange,
      handlePermissionChange,
      selectAllPermissions,
      deselectAllPermissions,
      hasPermissionChanges,
      handleSave,
      handleClose,
      handleOverlayClick
    };
  }
};
</script>

<style scoped>
/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes scaleIn {
  from { transform: scale(0.95); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}

.fixed.inset-0 {
  animation: fadeIn 0.2s ease-out forwards;
}

.bg-white.rounded-lg {
  animation: scaleIn 0.2s ease-out forwards;
}

/* 滚动条样式优化 */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 权限项悬停效果 */
.permission-item:hover {
  background-color: #f9fafb;
  padding-left: 2px;
  border-radius: 3px;
}

/* 禁用状态样式 */
input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
    